#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
生成默认图片资源的脚本
用于创建外卖、用户头像等默认图片
"""

import os
from PIL import Image, ImageDraw, ImageFont
import random

# 设置媒体文件根目录
BASE_DIR = os.path.dirname(os.path.abspath(__file__))
MEDIA_ROOT = os.path.join(BASE_DIR, 'media')

# 颜色配置
COLORS = {
    'primary': [(255, 107, 107), (255, 159, 64), (255, 206, 84), (75, 192, 192),
                (54, 162, 235), (153, 102, 255), (255, 99, 132)],
    'pastel': [(255, 179, 186), (255, 223, 186), (255, 255, 186), (186, 255, 201),
               (186, 225, 255), (220, 198, 255), (255, 198, 255)],
    'food': [(139, 69, 19), (255, 140, 0), (255, 215, 0), (34, 139, 34),
             (220, 20, 60), (255, 105, 180), (138, 43, 226)]
}

# 食品类别及对应的 emoji 图标
FOOD_CATEGORIES = {
    '汉堡': '🍔',
    '披萨': '🍕',
    '面条': '🍜',
    '寿司': '🍣',
    '米饭': '🍚',
    '鸡腿': '🍗',
    '薯条': '🍟',
    '三明治': '🥪',
    '沙拉': '🥗',
    '甜点': '🍰',
    '咖啡': '☕',
    '奶茶': '🧋',
    '果汁': '🧃',
    '冰淇淋': '🍦',
    '饺子': '🥟',
    '包子': '🥟',
    '炒饭': '🍛',
    '火锅': '🍲'
}


def create_gradient_background(width, height, color1, color2):
    """创建渐变背景"""
    base = Image.new('RGB', (width, height), color1)
    top = Image.new('RGB', (width, height), color2)
    mask = Image.new('L', (width, height))
    mask_data = []
    for y in range(height):
        mask_data.extend([int(255 * (y / height))] * width)
    mask.putdata(mask_data)
    base.paste(top, (0, 0), mask)
    return base


def create_user_portrait(filename, size=(300, 300)):
    """生成用户头像"""
    # 随机选择颜色
    bg_color = random.choice(COLORS['pastel'])
    
    # 创建图像
    img = Image.new('RGB', size, bg_color)
    draw = ImageDraw.Draw(img)
    
    # 绘制圆形头像框
    center_x, center_y = size[0] // 2, size[1] // 2
    radius = min(size) // 3
    
    # 绘制头部（圆形）
    draw.ellipse([center_x - radius, center_y - radius - 20,
                  center_x + radius, center_y + radius - 20],
                 fill=(255, 255, 255), outline=(200, 200, 200), width=3)
    
    # 绘制身体（半圆）
    draw.ellipse([center_x - radius * 1.2, center_y + radius - 40,
                  center_x + radius * 1.2, center_y + radius * 2 - 40],
                 fill=(255, 255, 255), outline=(200, 200, 200), width=3)
    
    # 保存图片
    os.makedirs(os.path.dirname(filename), exist_ok=True)
    img.save(filename, 'PNG')
    print(f"✓ 生成用户头像: {filename}")


def create_food_image(filename, food_name, emoji, size=(400, 400)):
    """生成食品图片"""
    # 随机选择两种颜色创建渐变背景
    color1 = random.choice(COLORS['primary'])
    color2 = random.choice(COLORS['pastel'])
    
    img = create_gradient_background(size[0], size[1], color1, color2)
    draw = ImageDraw.Draw(img)
    
    # 尝试使用系统字体
    try:
        # Windows 系统字体
        font_large = ImageFont.truetype("seguiemj.ttf", 120)  # Emoji 字体
        font_small = ImageFont.truetype("msyh.ttc", 40)  # 微软雅黑
    except:
        try:
            font_large = ImageFont.truetype("arial.ttf", 120)
            font_small = ImageFont.truetype("arial.ttf", 40)
        except:
            font_large = ImageFont.load_default()
            font_small = ImageFont.load_default()
    
    # 绘制 emoji（如果字体支持）
    center_x, center_y = size[0] // 2, size[1] // 2
    
    # 绘制白色圆形背景
    circle_radius = 120
    draw.ellipse([center_x - circle_radius, center_y - circle_radius - 30,
                  center_x + circle_radius, center_y + circle_radius - 30],
                 fill=(255, 255, 255, 200))
    
    # 尝试绘制 emoji
    try:
        bbox = draw.textbbox((0, 0), emoji, font=font_large)
        text_width = bbox[2] - bbox[0]
        text_height = bbox[3] - bbox[1]
        draw.text((center_x - text_width // 2, center_y - text_height // 2 - 30),
                  emoji, fill=(255, 255, 255), font=font_large)
    except:
        # 如果不支持 emoji，绘制一个简单的图形
        draw.ellipse([center_x - 60, center_y - 60,
                      center_x + 60, center_y + 60],
                     fill=(255, 200, 100), outline=(255, 255, 255), width=5)
    
    # 绘制食品名称
    try:
        bbox = draw.textbbox((0, 0), food_name, font=font_small)
        text_width = bbox[2] - bbox[0]
    except:
        text_width = len(food_name) * 20
    
    # 绘制文字背景
    padding = 15
    text_y = size[1] - 80
    draw.rectangle([center_x - text_width // 2 - padding, text_y - padding,
                    center_x + text_width // 2 + padding, text_y + 40],
                   fill=(255, 255, 255, 180))
    
    # 绘制文字
    draw.text((center_x - text_width // 2, text_y),
              food_name, fill=(50, 50, 50), font=font_small)
    
    # 保存图片
    os.makedirs(os.path.dirname(filename), exist_ok=True)
    img.save(filename, 'PNG')
    print(f"✓ 生成外卖图片: {filename} ({food_name})")


def create_default_takeout_image(filename, size=(400, 400)):
    """生成默认外卖图片"""
    # 创建渐变背景
    color1 = (255, 159, 64)
    color2 = (255, 206, 84)
    
    img = create_gradient_background(size[0], size[1], color1, color2)
    draw = ImageDraw.Draw(img)
    
    center_x, center_y = size[0] // 2, size[1] // 2
    
    # 绘制一个餐盘图标
    # 外圆
    draw.ellipse([center_x - 100, center_y - 100,
                  center_x + 100, center_y + 100],
                 fill=(255, 255, 255), outline=(200, 200, 200), width=5)
    
    # 内圆（装饰）
    draw.ellipse([center_x - 80, center_y - 80,
                  center_x + 80, center_y + 80],
                 outline=(220, 220, 220), width=3)
    
    # 绘制刀叉
    # 叉子
    fork_x = center_x - 30
    draw.line([fork_x, center_y - 50, fork_x, center_y + 50], fill=(150, 150, 150), width=5)
    draw.line([fork_x - 10, center_y - 50, fork_x - 10, center_y - 20], fill=(150, 150, 150), width=3)
    draw.line([fork_x, center_y - 50, fork_x, center_y - 20], fill=(150, 150, 150), width=3)
    draw.line([fork_x + 10, center_y - 50, fork_x + 10, center_y - 20], fill=(150, 150, 150), width=3)
    
    # 刀
    knife_x = center_x + 30
    draw.line([knife_x, center_y - 50, knife_x, center_y + 50], fill=(150, 150, 150), width=5)
    draw.polygon([knife_x - 8, center_y - 50, knife_x + 8, center_y - 50, knife_x, center_y - 60],
                 fill=(150, 150, 150))
    
    # 保存图片
    os.makedirs(os.path.dirname(filename), exist_ok=True)
    img.save(filename, 'PNG')
    print(f"✓ 生成默认外卖图片: {filename}")


def main():
    """主函数"""
    print("=" * 60)
    print("开始生成图片资源...")
    print("=" * 60)
    
    # 1. 生成默认用户头像
    print("\n[1/3] 生成用户头像...")
    user_dir = os.path.join(MEDIA_ROOT, 'users', 'default')
    create_user_portrait(os.path.join(user_dir, 'user_portrait.png'))
    
    # 生成额外的用户头像（不同颜色）
    for i in range(5):
        create_user_portrait(os.path.join(user_dir, f'user_portrait_{i+1}.png'))
    
    # 2. 生成默认外卖图片
    print("\n[2/3] 生成默认外卖图片...")
    takeout_dir = os.path.join(MEDIA_ROOT, 'takeouts', 'default')
    create_default_takeout_image(os.path.join(takeout_dir, 'takeout_portrait.png'))
    
    # 3. 生成各类食品图片
    print("\n[3/3] 生成各类食品图片...")
    for food_name, emoji in FOOD_CATEGORIES.items():
        filename = os.path.join(takeout_dir, f'{food_name}.png')
        create_food_image(filename, food_name, emoji)
    
    print("\n" + "=" * 60)
    print(f"✓ 完成！共生成 {len(FOOD_CATEGORIES) + 7} 张图片")
    print(f"图片保存位置: {MEDIA_ROOT}")
    print("=" * 60)


if __name__ == '__main__':
    main()

